package com.zimug.courses.security.basic.auth.service;

import com.zimug.courses.security.basic.auth.model.MyUserDetails;
import com.zimug.courses.security.basic.dao.MyUserDetailsMapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: liull
 * @Description: UserDetailsService实现类
 * @Date: Created in 20:54 2020/11/25
 * @Modified By:
 */
@Component
public class MyUserDetailsService implements UserDetailsService {
    private final MyUserDetailsMapper userDetailsMapper;

    // @Autowired可以省略
    public MyUserDetailsService(MyUserDetailsMapper userDetailsMapper) {
        this.userDetailsMapper = userDetailsMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 用户基础信息
        MyUserDetails details = userDetailsMapper.findUserDetailsByName(username);
        // 获取用户的角色列表
        List<String> roleCodes = userDetailsMapper.queryRolesByUsername(username);
        // 获取用户的权限列表
        List<String> authorities = userDetailsMapper.queryAuthoritiesByRoleCode(roleCodes);
        // roleCodes对应的
        roleCodes = roleCodes.stream().map(rc -> "ROLE_" + rc).collect(Collectors.toList());
        authorities.addAll(roleCodes);
        details.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", authorities)));
        return details;
    }
}
